import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

public class Tets5_pool {
    public static void main(String[] args) {
        /*核心线程池的大小*/
        int corePoolSize=3;
        //核心线程池的最大线程数
        int maxPoolSize=5;
        //线程的最大空闲时间
        long keepAliveTime=10;
        //时间单位
        TimeUnit unit=TimeUnit.SECONDS;//enum枚举 常量
        //阻塞队列容量为2 最多允许放入两个空闲任务
        BlockingQueue<Runnable>workQueue=new ArrayBlockingQueue<>(2);
        ThreadFactory threadFactory=new NameTreadFactory();
        RejectedExecutionHandler handler=new MyIgnorePolicy();
        ThreadPoolExecutor executor=null;
       try {
           //推荐的创建线程池的方式
           //不推荐使用现成的ApI创建线程池
           executor = new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);
           executor.prestartAllCoreThreads();
           //任务数量
           int count =10;
           for (int i=0;i<=count;i++){
               Task task=new Task(String.valueOf(i));
               executor.submit(task);//线程同时执行5个任务+2个队列 提交任务到线程池 还有三个任务无法执行
           }

       }finally {
           assert executor !=null; //断言 可开关 -ea -da
           executor.shutdown();
       }
    }
    static class NameTreadFactory implements ThreadFactory{
        private final AtomicInteger threadId=new AtomicInteger(1);

        @Override
        public Thread newThread(Runnable r) {
           Thread t=new Thread(r,"线程-"+threadId.getAndIncrement());//i++ => i 1+1 默值
            System.out.println(t.getName()+"已经被创建");
            return t;
        }
    }
    public static class MyIgnorePolicy implements RejectedExecutionHandler{

        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
            doLog(r,e);
        }
        private void doLog(Runnable runnable,ThreadPoolExecutor e){
            System.err.println("线程池"+e.toString()+runnable.toString()+"被拒绝执行");
        }
    }
    static class  Task implements Runnable{
        private String name;
        public Task(String name){
            this.name=name;
        }
        @Override
        public void run() {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        public String toString(){
            return "RunnableTask [name="+name+"]";
        }

    }
}
//任务类


